package com.easipass.framework.eirframeworkcore;

import com.easipass.framework.eirframeworkbeanshell.Message;
import com.easipass.framework.eirframeworkbeanshell.ScriptHandle;
import com.easipass.framework.eirframeworkcoredsl.AppNode;
import com.easipass.framework.eirframeworkcoredsl.AppParser;
import com.easipass.framework.eirframeworkcoredsl.LabelledServiceNode;
import com.easipass.framework.eirframeworkcoredsl.SinkDestinationNode;
import com.easipass.framework.eirframeworkjdbc.AppRepository;
import com.easipass.framework.eirframeworkjdbc.AppType;
import com.easipass.framework.eirframeworkjdbc.MessageLogService;
import com.easipass.framework.eirframeworkjdbc.ServiceRepository;
import com.easipass.framework.eirframeworkjdbc.model.App;
import com.easipass.framework.eirframeworkjdbc.model.Service;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @Autowired
    AppRepository appRepository;

    @Autowired
    ServiceRepository serviceRepository;

    @Autowired
    StreamFeignService streamFeignService;

    @Autowired
    MessageLogService messageLogService;

    @RequestMapping("/process/{service}")
    public void process(@PathVariable("service") String serviceName,
                        @RequestParam String name,
                        @RequestParam String content) {
        Message message = new Message(name, content, serviceName);
        Service service = serviceRepository.findByName(serviceName);
        AppNode appNode = parse(serviceName, service.getProcess(), true);
        ScriptHandle scriptHandle = new ScriptHandle();
        for (LabelledServiceNode functionNode : appNode.getServiceApps()) {
            for (LabelledServiceNode flowNode : functionNode.getSeries()) {
                App functionApp = appRepository.findByNameAndType(flowNode.getName(), AppType.SCRIPT.toString());
                scriptHandle.process(functionApp.getCode(), message);
                messageLogService.save(name,serviceName,functionApp.getName(),new Gson().toJson(message.getContent()));
            }
        }
        SinkDestinationNode sinkDestinationNode = appNode.getSinkDestinationNode();
        if (sinkDestinationNode != null) {
            App sinkApp = appRepository.findByNameAndType(sinkDestinationNode.getDestinationName(), AppType.SINK.toString());
            streamFeignService.putKafkaMsg(sinkApp.getName(), message.getContent().toString(), message.getName());
        }
    }

    AppNode parse(String serviceNmae, String serviceDefinition, boolean validate) {
        return new AppParser(serviceNmae, serviceDefinition, validate).parse();
    }
}
